<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;

/**
 * Costcompare控制器
 */
class Costcompare extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Advertisinglb();

        $this->validate = \app\admin\validate\Advertisinglb::class;
    }

    //首页
    public function index()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();

        $where2 = array();
        $b_time = date('Y-m-d 00:00:00', strtotime('-1 days')); //昨天跟今天的数据
        // $b_time = date('Y-m-d 00:00:00', time());//今天没数据
        $e_time = date('Y-m-d 00:00:00', strtotime('+1 days'));
        $where2[] = ['create_time', '>=', $b_time];
        $where2[] = ['create_time', '<=', $e_time];
        foreach ($where as $k => $v) {
            if ($v[0] == 'create_time') {
                $where2 = array();
                break;
            }
        }

        // halt($where);
        $list = $this->model
            ->field("SUM(`cost`) as cost,admin_id,create_time")
            ->where($where)
            ->where($where2)
            ->group('admin_id')
            ->paginate($limit);

        $lists = $list->items();
        foreach ($lists as $k => $v) {
            //通过admin_id 查询这个时间段的蓝标花费
            $cost =  table('advertising')->where($where)->where($where2)->where(['admin_id' => $v['admin_id']])->sum('cost');
            $admin = table('system_admin')
                ->where('id', $v['admin_id'])
                ->find();
            $lists[$k]['lbcost'] = !empty($v['cost']) ? round($v['cost'], 2) : 0;
            $lists[$k]['cost'] = !empty($cost) ? round($cost, 2) : 0;
            $lists[$k]['admin_id'] = !empty($admin) ? $admin['nickname'] : 0;
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $lists,
        ];
        return json($data);
    }
}
